import json
import socket
import threading
import os


class TransportServer:
    def __init__(self, receive_message):
        # 存储所有客户端连接的列表
        self.clients = []
        self.console = receive_message

        self.listening = True
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.server_socket.bind(('0.0.0.0', 6985))  # 绑定所有网络接口

    def transport_server(self):
        """服务端主逻辑"""
        self.server_socket.listen(10)
        print("Server listening on port 6985...")
        try:
            while True:
                client_socket, addr = self.server_socket.accept()
                self.clients.append(client_socket)  # 将新客户端添加到连接列表中
                self.handle_client(client_socket, addr)
        except OSError as e:
            print('transport_server: ', e)
            self.server_socket.close()

    def start(self):
        threading.Thread(target=self.transport_server, daemon=True).start()

    def stop(self):
        """手动停止服务器"""
        self.listening = False  # 设置停止标志
        self.server_socket.close()  # 关闭服务器套接字
        print("Server is shutting down.")

    def handle_client(self, client_socket, addr):
        """处理单个客户端的连接"""
        print(f"Connection from {addr} established.")
        try:
            while True:
                # 接收客户端发送的消息
                message = client_socket.recv(1024)
                if not message:
                    break  # 如果客户端断开连接

                self.console(message.decode('utf-8'))
        except Exception as e:
            print(f"Error handling client {addr}: {e}")
        finally:
            # 从客户端列表中移除断开的连接
            self.clients.remove(client_socket)
            client_socket.close()

    def send_message(self, message):
        for client in self.clients:
            client.send(json.dumps(message).encode('utf-8'))

    def send_file(self, message):
        """发送文件给客户端"""
        filepath = os.path.join(os.getcwd(), 'chat_files', *(message['filepath'].split('/')))
        if not os.path.exists(filepath):
            return
        print("self.clients", self.clients)
        for client in self.clients:
            file_size = os.path.getsize(filepath)
            message['filesize'] = file_size
            client.send(json.dumps(message).encode('utf-8'))

            with open(filepath, 'rb') as f:
                while chunk := f.read(1024):
                    client.send(chunk)
